// radio
window.Vue && Vue.component('layui-radio', {
	template: `
<div class="layui-unselect layui-form-radio" :class="classs" @click="onCheck">
	<div style="display: none !important;">
		<input type="radio" :name="name" :value="value" lay-ignore @change="onChange" ref="radio" :checked="isChecked" />
	</div>
	<i class="layui-anim layui-icon">{{isChecked?"":""}}</i>
	<div><slot></slot></div>
</div>
`,
	model: {
		prop: 'checked',
		event: 'change'
	},
	props: {
		value: {
			type: null,
			default: true
		},
		checked: null,
		name: String,
	},
	data() {
		return {
			selectValue: null
		};
	},
	computed: {
		isChecked: function() {
			return this.value == this.selectValue;
		},
		classs: function() {
			return {
				'layui-form-radioed': this.isChecked
			};
		}
	},
	created: function() {
		this.selectValue = this.checked;
		if (this._getRadioGroup) {
			this.selectValue = this._getRadioGroup.value;
		}
	},
	methods: {
		onCheck: function() {
			if (typeof this.value === 'boolean') {
				this.selectValue = true;
				this.$emit('change', true);
			} else {
				this.selectValue = this.value;
				this.$refs.radio.checked = true;

				this.dispatchEvent();
				this.$emit('change', this.value);
			}
		},
		dispatchEvent() {
			if (!this.name) {
				return;
			}

			const radios = document.getElementsByName(this.name);
			const evt = document.createEvent("HTMLEvents");
			evt.initEvent("change", false, true);

			if (typeof this.value === 'boolean') {
				evt.value = false;
			} else {
				evt.value = this.selectValue;
			}

			radios.forEach((radio) => {
				if (radio === this.$refs.radio) {
					return;
				}

				radio.checked = false;
				radio.dispatchEvent(evt);
			});
		},
		onChange(e) {
			this.selectValue = e.value;
		},
	},
	watch: {
		checked: function(value) {
			this.selectValue = value;
		}
	}
});
